const data = [
  {
    id: 1,
    pid: 0,
  },
  {
    id: 2,
    pid: 0,
  },
  {
    id: 3,
    pid: 1,
  },
  {
    id: 4,
    pid: 2,
  },
  {
    id: 5,
    pid: 3,
  },
];

console.time("aaa");
// (1)
function formatDataTree(data) {
  const parentD = data.filter((o) => o.pid === 0),
    children = data.filter((o) => o.pid !== 0);

  function getTree(parentD, children) {
    parentD.map((p) => {
      children.map((c, i) => {
        if (c.pid === p.id) {
          const _children = JSON.parse(JSON.stringify(children));
          getTree([c], _children);
          if (!p.children) {
            p.children = [];
          }
          children.splice(i, 1);
          p.children.push(c);
        }
      });
    });
    return parentD;
  }

  return getTree(parentD, children);
}

// (2)
function formatDataTree(data) {
  let _data = JSON.parse(JSON.stringify(data));
  return _data.filter((p) => {
    const _arr = _data.filter((c) => c.pid === p.id);
    _arr.length && (p.children = _arr);
    console.log(p)
    return p.pid === 0;
  });
}
console.log(formatDataTree(data));
console.timeEnd("aaa");
